package com.link.base.base.policy.controller;

import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.policy.model.Policy;
import com.link.base.base.policy.service.PolicyService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 * @comments 政策请求处理
 */
@Controller
@RequestMapping("/link/policy")
public class PolicyController extends BasicController<Policy> {

    @Resource
    private PolicyService policyService;

    @Resource
    private AttachmentService attachmentService;

    @Override
    public BasicService<Policy> getBasicService() throws Exception {
        return policyService;
    }

    /**
     * 更新政策图片
     */
    @RequestMapping(value = "/uploadImg")
    @ResponseBody
    public Map<String, Object> uploadImg(@RequestBody Policy entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile myfile = multipartRequest.getFile("myfile");
        String base = "base";
        try {
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServiceException("PUBLIC-002");
            }
            if (myfile == null) {
                throw new ServiceException("PUBLIC-013");
            }
            Policy oldEntry = policyService.queryById(entity);
            if (oldEntry == null) {
                throw new ServiceException("PUBLIC-014");
            }
            try {
                Long oldImgId = oldEntry.getImgId();
                if (oldImgId == null) {
                    Attachment param = new Attachment();
                    param.setId(oldImgId);
                    attachmentService.deleteById(param);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
            // 插入附件表
            Attachment imgObj = new Attachment();
            imgObj.setHeadId(entity.getId());
            imgObj.setModuleType("Policy Img");
            LCLogger.info().withMessageKey("uploadImg")
                    .withMessage("上传附件记录！").flush();
            // 附件上传
            attachmentService.upload(myfile, imgObj);
            LCLogger.info().withMessageKey("uploadImg")
                    .withMessage("插入附件记录！").flush();
            // 向附件表插入附件基础信息
            attachmentService.insert(imgObj);
            entity.setImgId(imgObj.getId());
            policyService.imgIdUpdate(entity);
            //审计追踪新建记录
            Policy newEntry = policyService.queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>根据id获取政策完成信息，头、政策、范围、规则、条件、结果</p>
     *
     * @author yrf
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getPolicyById")
    @ResponseBody
    public Map<String, Object> getPolicyById(@RequestBody Policy entity, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Policy policy = policyService.getPolicyById(entity);
            result.put("success", true);
            result.put("result", policy);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>新建一个政策，包括头、范围、规则等</p>
     *
     * @author yrf
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/newPolicy")
    @ResponseBody
    public Map<String, Object> newPolicy(@RequestBody Policy entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            policyService.insertPolicy(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>更新一个政策，包括头、范围、规则等</p>
     *
     * @author yrf
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/updatePolicy")
    @ResponseBody
    public Map<String, Object> updatePolicy(@RequestBody Policy entity, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            policyService.updatePolicy(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据产品ID查询符合的促销政策
     */
    @RequestMapping(value = "/queryByProdId")
    @ResponseBody
    public Map<String, Object> queryByProdId(@JsonParam QueryParams qps, @JsonParam Policy entity, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        String  flag = "Y";
        if (flag.equals(YmlConstants.getDmsForSiebel())) {
            result = null;
        } else {
            try {
                Policy t = (Policy) BasicModel.transformClass(entity.getClass(), qps);
                beforQueryAllOrExample(t, request);
                beforQueryExample(t, request);

                Long accntId = UserUtil.getUser().getAcctId();
                if (accntId == null) {
                    throw new ServiceException("POLICY-014");
                }
                t.setAttr1(accntId.toString());
                String prodId = t.getAttr2();
                if (StringUtils.isBlank(prodId)) {
                    throw new ServiceException("POLICY-019");
                }

                List<Policy> list = getBasicService().queryByExamplePage(t);
                result.put("success", true);
                result.put("rows", list);
                this.pushCurrentDataCache(list, session.getId(), "base", false);
                result.put("total", getCount(t, list.size()));
            } catch (Exception e) {
                LCLogger.withException(e);
                result.put("success", false);
                result.put("rows", new ArrayList<Policy>());
                result.put("result", e.getMessage());
            }
        }
        return result;
    }

    /**
     * @param saleOrder 订单对象
     * @param request   请求
     * @param response  返回
     * @return map对象
     * @auther HuangLJ
     */
    @RequestMapping(value = "/getPolicyOrder")
    @ResponseBody
    public Map<String, Object> getPolicyOrder(@RequestBody SaleOrder saleOrder, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            policyService.getPolicy(saleOrder);
            result.put("success", true);
            result.put("rows", saleOrder);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/checkPolicyOrder")
    @ResponseBody
    public Map<String, Object> checkPolicy(@RequestBody SaleOrder saleOrder, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
//          policyService.getPolicy(saleOrder);
            result.put("success", true);
            result.put("rows", saleOrder);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * HuangLJ 更新政策主要组织Id
     *
     * @param policy   政策
     * @param request  请求
     * @param response 响应
     * @return 返回Map
     */
    @RequestMapping(value = "/updateMainOrg")
    @ResponseBody
    public Map<String, Object> updatePolicyMainOrg(@RequestBody Policy policy, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            policyService.updatePolicyMainOrg(policy);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
